package com.saltedfish.tool.receiver;



import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import androidx.core.content.FileProvider;

import java.io.File;

/**
 *
 */
public class ApkInstallReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long downloadApkId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                installApk(context, downloadApkId);
        }
    }

    private static void installApk(Context context, long downloadApkId) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri downloadFileUri = dManager.getUriForDownloadedFile(downloadApkId);
    //   XLog.e("test", "fileLocation:"+downloadFileUri.toString());
        if (downloadFileUri != null) {
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                File file = new File(Environment.getExternalStorageDirectory()+ File.separator+"咸鱼Flag.apk");
                Uri apkUri = FileProvider.getUriForFile(context,context.getPackageName()+".fileprovider",file);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                context.startActivity(install);
            }else{
                install.setDataAndType(Uri.parse("file://"+ Environment.getExternalStorageDirectory()+ File.separator+"咸鱼Flag.apk"), "application/vnd.android.package-archive");
                context.startActivity(install);
            }
        }
    }
}
